//
//  UISearchViewController.m
//  WXMusic
//
//  Created by lanou3g on 15/9/9.
//  Copyright (c) 2015年 漫步人生路. All rights reserved.
//

#import "UISearchViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "MBProgressHUD.h"
@interface UISearchViewController ()<CLLocationManagerDelegate,UISearchBarDelegate>
@property(nonatomic, strong) CLLocationManager *manager;
@property(nonatomic, strong) CLLocation *location;
@property(nonatomic,strong)CLGeocoder *geocoder;
@property (nonatomic ,strong) MBProgressHUD *hud;

@end

@implementation UISearchViewController
-(CLGeocoder *)geocoder
 {
        if (_geocoder==nil) {
                 _geocoder=[[CLGeocoder alloc]init];
             }
         return _geocoder;
     }
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0,20, kWidth, 50)];
    self.searchBar.delegate = self;
   self.searchBar.placeholder = @"输入你想搜索的城市";
    self.searchBar.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.searchBar];
    _manager = [[CLLocationManager alloc] init];
    //判断如果用户没有处理过弹框，就去请求处理
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        //请求在应用程序使用的时候使用定位；
        [_manager requestWhenInUseAuthorization];
        
    }
    //设置定位的时候精准度，定位越精准就越耗电。
    _manager.desiredAccuracy = kCLLocationAccuracyBest;
    //设置定位的频率（每隔多少米会定位一次）
    _manager.distanceFilter = 1.0;
    _manager.delegate = self;
    //开始定位
    [_manager startUpdatingLocation];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


// 键盘中，搜索按钮被按下，执行的方法


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
   
    NSString *address = searchBar.text;
    if (address.length == 0) {
        return;
    }
    
   [self.geocoder geocodeAddressString:address completionHandler:^(NSArray *placemarks, NSError *error) {
       if (error || placemarks.count==0) {
           searchBar.text = @"你输入的地址没找到，可能在月球上";
       }else
       {
           for (CLPlacemark *placemark in placemarks) {
            NSLog(@"name=%@ locality=%@ country=%@ postalCode=%@",placemark.name,placemark.locality,placemark.country,placemark.postalCode);
                           }
             CLPlacemark *firstPlacemark=[placemarks firstObject];
           NSString *str  =  firstPlacemark.locality;
           //NSString * strr = [str substringToIndex:2];
           [[NSUserDefaults standardUserDefaults] setObject: str forKey:@"city"];
           NSLog(@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"city"]);
           [[weatherHandle shareWetherHandle] relodeData];

       }
   }];
   
    [self.searchBar resignFirstResponder];
}

@end
